#region Copyright
// Copyright (c) 2008, Mitchell Humphrey & Co.
// This software is a copyrighted, licensed program which is the
// property of Mitchell Humphrey & Co.  Permission to use, copy
// or distribute this program in any form -- source, executable,
// or otherwise -- is granted only by written license obtained
// from Mitchell Humphrey & Co.  All rights reserved.  No part
// of the publication may be reproduced, stored in a retrieval
// system, or transmitted in any way without written permission
// of Mitchell Humphrey & Co.
#endregion Copyright

#region License

// This software is released under the Microsoft Public License (Ms-PL)

//Microsoft Public License (Ms-PL)
//This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

//Definitions
//The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution.
//Grant of Rights
//(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
//(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
//Conditions and Limitations
//(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. 
//(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. 
//(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. 
//(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. 
//(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees, or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.

#endregion

#region Revision History

//REVISION HISTORY:
//John Hoven 12/02/2008 Original

#endregion

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;
using System.Web.Services.Protocols;
using System.Xml;
using System.Globalization;

namespace MitchellHumphrey.Plugins
{
    /// <summary>
    ///     Set Date Only fields to noon.
    ///     Stage:  Pre
    ///     Entity Name:  Any
    ///     Messages:  Create, Update
    ///     Rank:  150 - This plugin should execute after all plug-ins containing business logic.
    ///     Syncronous?  True.
    /// </summary>
    public sealed class DateOnlyChangePluginCreateUpdateRank150 : IPlugin
    {
        // Configuration Storage
        private Dictionary<string, string[]> _attributes = new Dictionary<string, string[]>();
        public Dictionary<string, string[]> AttributeDict
        {
            get
            {
                return _attributes;
            }
        }


        /// <summary>
        /// Configuration for this plugin.  Specifies which date only attributes we will process.
        ///     We will not use the metadata service initially.
        /// </summary>
        /// <param name="configuration">
        /// The configuration is an XML fragment formated as follows:
        /// &lt;dateOnlyConfiguration&gt;
        ///   &lt;entity name="entity"&gt;
        ///     &lt;attribute name="attribute"/&gt;
        ///     ...
        ///   &lt;/entity&gt;
        ///   ...
        /// &lt;/dateOnlyConfiguration&gt;
        /// </param>
        /// <param name="secureConfiguration">Not used</param>
        public DateOnlyChangePluginCreateUpdateRank150(string configuration, string secureConfiguration)
        {
            if (!string.IsNullOrEmpty(configuration))
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(configuration);

                XmlNodeList entities = doc.SelectNodes("/dateOnlyConfiguration/entity");
                foreach (XmlNode entity in entities)
                {
                    if (entity.Attributes["name"] == null)
                        continue;
                    string name = entity.Attributes["name"].Value;


                    XmlNodeList attributes = entity.SelectNodes("attribute");
                    List<string> result = new List<string>();
                    foreach (XmlNode attribute in attributes)
                    {
                        if (attribute.Attributes["name"] == null)
                            continue;
                        result.Add(attribute.Attributes["name"].Value);
                    }
                    // Store in lists so they will be processed on create/updates
                    if (result.Count > 0)
                    {
                        _attributes.Add(name, result.ToArray());
                    }
                }
            }
        }
        #region IPlugin Members
        public void Execute(IPluginExecutionContext context)
        {
            if (context.InputParameters.Contains(ParameterName.Target))
            {
                // Find our target
                DynamicEntity den = (DynamicEntity)context.InputParameters[ParameterName.Target];
                if (context.MessageName != MessageName.Create && context.MessageName != MessageName.Update)
                    throw new InvalidPluginExecutionException("Registration");

                // Make sure this entity needs to be updated
                if (den == null || _attributes == null || !_attributes.ContainsKey(den.Name))
                    return;

                // Get a system service
                ICrmService service = context.CreateCrmService(false);

                // Get the attribute configuration
                string[] attributesInEntity = _attributes[den.Name];
                if (attributesInEntity == null)
                    return;

                // Find each attribute that was set.  If its a crm date time (ignore misconfiguration)
                // then get the user time for that value.  Format to a univeral time using the user time
                // at noon, so the entire globe see's the same date.
                foreach (string attributeInEntity in attributesInEntity)
                {
                    if (den.Properties.Contains(attributeInEntity))
                    {
                        object prop = den[attributeInEntity];
                        if (prop is CrmDateTime)
                        {
                            CrmDateTime dtProp = prop as CrmDateTime;
                            if (dtProp.IsNull == false)
                            {
                                // Get the date in the user's time zone
                                DateTime? userDate = GetUserDate(service, dtProp, context.UserId);
                                if (!userDate.HasValue)
                                {
                                    continue;
                                }
                                else
                                {
                                    // Format to noon universal time using the user's date.  This way -12, +11 hours
                                    // from UTC will all see the the date in the right date.
                                    dtProp.Value = String.Format(CultureInfo.InvariantCulture,
                                        "{0:yyyy-MM-dd}T12:00:00Z", userDate.Value);
                                }
                            }
                        }
                    }
                }
            }
        }
        #endregion
        /// <summary>
        ///     Get Noon in the user's time zone.  If the call was made by the System User 
        ///     (usually another plugin running not-as-user), will return UTC.
        /// </summary>
        /// <param name="pService"></param>
        /// <param name="pDateWithTime"></param>
        /// <param name="pUserID"></param>
        /// <returns></returns>
        private DateTime? GetUserDate(ICrmService pService, CrmDateTime pDateWithTime, Guid pUserID)
        {
            // Get the value of the crm date time
            if (string.IsNullOrEmpty(pDateWithTime.Value))
            {
                // Bad CrmDateTime.  I'll ignore it, they'll get an exception from CRM anyway.
                return null;
            }

            DateTime? universalTime = null;
            DateTime? userTime = null;
            
            // See SDK for CrmDateTime.Value property.  Value will be in one of 3 formats:
            // yyyy-MM-ddTHH:mm:ss  (User Time Only)
            // yyyy-MM-ddTHH:mm:ss Z (Universal)
            // yyyy-MM-ddTHH:mm:ss Offset (Both), offset is + or -##:##
            // 1.  End in a Z.  It is a universal time
            // 2.  End in an offset.  It is a user time, specifying the offset
            // 3.  Unspecified.  CRM will assume it is in user time and convert it to universal
                        
            string dateTimeString = pDateWithTime.Value.Trim();
            DateTime time = DateTime.Parse(dateTimeString, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
            // If it ends in a Z, it is universal time
            if (dateTimeString.ToUpper().EndsWith("Z"))
            {
                universalTime = new DateTime?(time);
            }
                // Contains an offset, we can infer both
            else if ((dateTimeString.Contains("+") || dateTimeString.Contains("-")) && dateTimeString.Contains(":"))
            {
                // Chop off the offset to create the user time.  The DateTime.Kind will be Unspecified.
                // The universal time using the offset will have a DateTime.Kind of UTC.
                string unspecfiedDateTimeString = dateTimeString.Substring(0, dateTimeString.Length - 9);
                userTime = new DateTime?(DateTime.Parse(unspecfiedDateTimeString, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal));
                universalTime = new DateTime?(time);
            }
            else
            {
                // If neither is provided then we can assume a DateTime.Kind of unspecified and use that for our user time.
                userTime = new DateTime?(time);
            }

            // If we have a user time after parsing, return it.  Otherwise we'll use the web services
            // to convert the universal time to a user date
            if (userTime.HasValue)
                return userTime;

            // Get the timezone code for the user.  When using the web-forms, this will never be hit.  It will
            // only be hit when providing a UTC only date through the web services.
            RetrieveUserSettingsSystemUserRequest request = new RetrieveUserSettingsSystemUserRequest();
            request.ColumnSet = new ColumnSet(new string[] { "timezonecode" });
            request.EntityId = pUserID;
            request.ReturnDynamicEntities = true;
            int timezoneCode = 0;
            // If we're actually running in the context of the system user (not just using crm service as
            // system), then this will fail because there are no user settings.  Keep UTC.
            try
            {
                RetrieveUserSettingsSystemUserResponse response = (RetrieveUserSettingsSystemUserResponse)
                    pService.Execute(request);
                DynamicEntity _userSettings = (DynamicEntity)response.BusinessEntity;
                if (_userSettings != null && _userSettings.Properties.Contains("timezonecode"))
                    timezoneCode = ((CrmNumber)_userSettings["timezonecode"]).Value;
            }
            catch (SoapException) 
            { 
                // To do:  catch the right error code only
            }
            // Convert universal time to user-local
            LocalTimeFromUtcTimeRequest requestFromUtc = new LocalTimeFromUtcTimeRequest();
            requestFromUtc.TimeZoneCode = timezoneCode;
            requestFromUtc.UtcTime = pDateWithTime;

            LocalTimeFromUtcTimeResponse responseFromUtc = (LocalTimeFromUtcTimeResponse)pService.Execute(
                requestFromUtc);
            return responseFromUtc.LocalTime.UserTime;
        }
    }

}
